package dao

import (
	"6-11zk/inits"
	"6-11zk/model"
)

func SupplierCreate(supplier *model.Supplier) error {
	return inits.DB.Debug().Create(&supplier).Error
}

func SupplierList(pages, size int, name string, peo string, address string) (result []*model.Supplier, err error) {
	page := pages
	if page <= 0 {
		page = 1
	}

	pageSize := size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	tx := inits.DB.Debug()
	if name != "" {
		tx = tx.Where("supplier_name LIKE ?", "%"+name+"%")
	}
	if peo != "" {
		tx = tx.Where("contacts LIKE ?", "%"+peo+"%")
	}
	if address != "" {
		tx = tx.Where("address LIKE ?", "%"+address+"%")
	}
	err = tx.Order("created_at desc").Offset(offset).Limit(pageSize).Find(&result).Error
	if err != nil {
		return nil, err
	}
	return
}
